<template>
  <div>
    <Card>
      <Form
        ref="postFormRef"
        :model="postForm"
        :rules="postFormRule"
        label-position="left"
        :label-width="100"
      >
        <FormItem label="文章标题" prop="post_name">
          <Input
            v-model="postForm.post_name"
            placeholder="请输入文章标题..."
          ></Input>
        </FormItem>
        <mavon-editor
          ref="markdown"
          style="z-index: 0"
          v-model="postForm.detail.pd_content_raw"
          @save="save"
          :codeStyle="codeStyle"
          :boxShadow="false"
        />
        <div style="height: 20px"></div>
        <FormItem label="文章描述">
          <Input
            v-model="postForm.post_describe"
            type="textarea"
            placeholder="请输入文章描述,不输入默认是文章前100字"
            :autosize="{ maxRows: 3, minRows: 3 }"
          ></Input>
        </FormItem>
        <Row>
          <Col :span="12">
            <FormItem label="文章封面图">
              <UploadImage v-model="postForm.post_cover" />
            </FormItem>
          </Col>
          <Col :span="12">
            <Col :span="12">
              <FormItem label="是否允许赞赏">
                <i-switch
                  v-model="postForm.detail.pd_is_reward"
                  size="large"
                  :true-value="0"
                  :false-value="1"
                >
                  <span slot="open">On</span>
                  <span slot="close">Off</span>
                </i-switch>
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="是否允许评论">
                <i-switch
                  v-model="postForm.detail.pd_is_comment"
                  size="large"
                  :true-value="0"
                  :false-value="1"
                >
                  <span slot="open">On</span>
                  <span slot="close">Off</span>
                </i-switch>
              </FormItem>
            </Col>
          </Col>
        </Row>

        <Row>
          <Col :span="12">
            <FormItem label="分类" style="width: 300px; ">
              <Select v-model="postForm.cate_id">
                <Option
                  :value="category.cate_id"
                  :key="category.cate_id"
                  v-for="category in categories"
                  >{{ category.cate_name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="标签">
              <CheckboxGroup v-model="postForm.tags">
                <Checkbox
                  :label="tag.tag_id"
                  v-for="tag in tags"
                  :key="tag.tag_id"
                >
                  <span>{{ tag.tag_name }}</span>
                </Checkbox>
              </CheckboxGroup>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col :span="12">
            <FormItem label="是否加密">
              <i-switch
                v-model="postForm.post_is_encrypted"
                size="large"
                :true-value="0"
                :false-value="1"
              >
                <span slot="open">On</span>
                <span slot="close">Off</span>
              </i-switch>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="密码">
              <Input
                :disabled="postForm.post_is_encrypted !== 0"
                type="password"
                v-model="postForm.detail.pd_pwd"
                password
              ></Input>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <Row class="button-group">
        <Button type="primary" @click="publish">发布文章</Button>
        <Button type="warning">放到草稿箱</Button>
        <Button type="error">丢弃</Button>
      </Row>
    </Card>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import UploadImage from "@/components/admin/UploadImage";
export default {
  name: "PostAddAndEdit",
  computed: {
    ...mapGetters(["codeStyle"])
  },
  data() {
    return {
      post_id: null,
      categories: [],
      tags: [],
      postForm: {
        post_name: "",
        post_id: null,
        post_describe: "",
        post_cover: "",
        post_is_encrypted: 0,
        post_status: 0,
        detail: {
          pd_content_raw: "",
          pd_content: "",
          pd_is_reward: 0,
          pd_is_comment: 0,
          pd_pwd: ""
        },
        cate_id: null,
        tags: []
      },
      postFormRule: {
        post_name: [
          { required: true, message: "please input post name", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    ...mapActions([
      "fetchBLogCategory",
      "fetchBlogTags",
      "savePost",
      "fetchPost",
      "editPost"
    ]),
    async getPost() {
      const res = await this.fetchPost(this.post_id);
      if (res.code === 2000) {
        this.$Message.success(`get post detail successful`);
        this.postForm = res.data;
        if (this.postForm.post_is_encrypted) {
          this.postForm.detail.pd_pwd = "******";
        }
      } else {
        this.$Message.error("get post detail failed");
      }
    },
    save() {
      this.$Message.info("文章已暂存");
      this.$set(
        this.postForm,
        "detail.pd_content_raw",
        this.$refs.markdown.d_value
      ); // html
      this.$set(
        this.postForm,
        "detail.pd_content",
        this.$refs.markdown.d_render
      ); //md
    },
    publish() {
      this.save();
      this.prepare();
      this.postForm.post_status = 0;
      this.$refs.postFormRef.validate(async isValid => {
        if (!isValid) {
          this.$Message.error("表单验证不通过");
          return;
        }
        let res;
        let code;
        if (!this.post_id) {
          res = await this.savePost(this.postForm);
          code = 2001;
        } else {
          code = 2002;
          res = await this.editPost({
            id: this.post_id,
            formData: Object.assign(this.postForm, this.postForm.detail)
          });
        }
        if (res.code === code) {
          this.$Message.success("保存文章成功");
          await this.$router.push({ name: "PostList" });
          return;
        }
        this.$Message.error("保存文章中失败");
      });
    },
    prepare() {
      this.postForm.detail.pd_pwd = this.$md5(this.postForm.detail.pd_pwd);
    },
    async getCategories() {
      const res = await this.fetchBLogCategory();
      if (res.code !== 2000) {
        this.$Message.error("获取分类列表失败");
      }
      this.$Message.success("获取分类列表成功");
      this.categories = res.data.content;
    },
    async getTags() {
      const res = await this.fetchBlogTags();
      if (res.code !== 2000) {
        this.$Message.error("获取标签列表失败");
      }
      this.$Message.success("获取标签列表成功");
      this.tags = res.data.content;
    }
  },
  components: {
    UploadImage
  },
  created() {
    this.post_id = this.$route.query.id;
    if (this.post_id) {
      this.getPost();
    }
    this.getCategories();
    this.getTags();
  }
};
</script>

<style lang="less" scoped>
.button-group {
  .ivu-btn {
    float: right;
    margin-left: 20px;
  }
}
</style>
